import { useLazyQuery, useMutation } from "@apollo/client";
import {
  getTimetableInfo_simple_service,
  getTimetablesByCourse_service,
  reserveCourse_service,
} from "../../graphql/timetable";
import { TimetableType } from "../../types/timetable/inex";

export const useGetTimetablesByCourse = () => {
  const [fun, { loading }] = useLazyQuery(getTimetablesByCourse_service, {
    fetchPolicy: "network-only",
  });

  const getTimetablesByCourse = async (courseId: string) => {
    const res = await fun({
      variables: {
        courseId,
      },
    });
    const { data, message, code, page } = res.data.getTimetablesByCourse as {
      data: TimetableType[];
      message: string;
      code: boolean;
      page: { total: number };
    };
    return {
      data,
      message,
      code,
      page,
    };
  };

  return { getTimetablesByCourse, loading };
};

export const useReserveCourse = () => {
  const [fun, { loading }] = useMutation(reserveCourse_service);

  const reserveCourse = async (
    courseId: string,
    cardRecordId: string,
    timetableId: string,
    orgId: string
  ) => {
    const res = await fun({
      variables: {
        courseId,
        cardRecordId,
        timetableId,
        orgId,
      },
    });
    return res.data.reserveCourse as { code: boolean; message: string };
  };

  return { reserveCourse, loading };
};

export const useGetTimetableInfo_simple = () => {
  const [fun, { loading }] = useLazyQuery(getTimetableInfo_simple_service);

  const getTimetableInfo = async (id: string) => {
    const res = await fun({
      variables: { id },
    });
    return res.data.getTimetableInfo.data as {
      id: string;
      startTime: string;
      endTime: string;
      classDay: Date;
    };
  };

  return { getTimetableInfo, loading };
};
